<?php

namespace app\cash\model;

use app\beautiful\model\goods\GoodsGroupDetailModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\common\model\CommonModel;
use app\stores\model\order\ReasonModel;
use think\facade\Db;


class CartDetailModel extends CommonModel{

    protected  $name = 'beautiful_cart_detail';

    protected  $pk   = 'cart_detail_id';
    /**
     * 模型写入前事件（钩子函数）
     */
    public static function onBeforeInsert($model)
    {
        $model->set("add_time", date('Y-m-d H:i:s'));
        $model->set("add_ip", request()->ip());
    }
    public static function list($where,$order,$page=0,$limit=0,$field='*'){
        $query = Db::name('beautiful_cart_detail')
            ->where(['is_delete'=>0])
            ->when(isset($where['cart_id']),function ($query) use ($where){
                $query->where(['cart_id'=>$where['cart_id']]);
            })
            ->when(isset($where['member_id']),function ($query) use ($where){
                $query->where(['member_id'=>$where['member_id']]);
            })
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['shop_id'=>$where['shop_id']]);
            })
            ->field($field);

        $count = $query->count();
        $query = $query->order($order);
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list = $query->field($field)
            ->select()
            ->toArray();

        if(!empty($list)){
            foreach ($list as &$v){
                $group_detail = GoodsGroupDetailModel::getById(['goods_group_detail_id'=>$v['goods_group_detail_id'],'is_delete'=>0]);
                $v['goods_name'] = $group_detail['name'];
                $v['sku_name'] = $group_detail['sku_name'];
                $v['unit'] = $group_detail['unit'];
                $v['num'] = $group_detail['num'];
            }

        }

        return compact('count','list');
    }
    public static function up($data,$where)
    {
        return self::update($data,$where);
    }
}

